<template>
	<div class="mc-popup-select-wrap">
		<Popover
			ref="popover"
			placement="bottom-start"
			width="700"
			trigger="click"
			:disabled="selectDisabled"
			class="popover-container"
			@after-enter="openDialog"
		>
			<template #reference>
				<div
					class="el-select"
				>
					<div
						v-if="multiple"
						ref="tags"
						class="el-select__tags"
						:style="{
							'max-width': inputWidth - 32 + 'px',
							'width': '100%',
							'cursor': 'pointer',
						}"
					>
						<span v-if="collapseTags && tagsList.length">
							<Tag
								:closable="!selectDisabled"
								:size="collapseTagSize"
								type="info"
								disable-transitions
								@close="deleteTag($event, 0)"
							>
								<span class="el-select__tags-text">{{tagsList[0][relationField]}}</span>
							</Tag>
							<Tag
								v-if="tagsList.length > 1"
								:closable="false"
								type="info"
								disable-transitions
							>
								<span class="el-select__tags-text">+ {{tagsList.length - 1}}</span>
							</Tag>
						</span>
						<transition-group
							v-if="!collapseTags"
							@after-leave="resetInputHeight"
						>
							<Tag
								v-for="(item, i) in tagsList"
								:key="item[propsValue]"
								:size="collapseTagSize"
								:closable="!selectDisabled"
								type="info"
								disable-transitions
								@close="deleteTag($event, i)"
							>
								<span class="el-select__tags-text">{{item[relationField]}}</span>
							</Tag>
						</transition-group>
					</div>
					<Input
						ref="reference"
						v-model="innerValue"
						type="text"
						:placeholder="currentPlaceholder"
						:disabled="selectDisabled"
						readonly
						:validate-event="false"
						:tabindex="multiple ? '-1' : null"
						@mouseenter.native="inputHovering = true"
						@mouseleave.native="inputHovering = false"
					>
						<template #suffix>
							<i
								v-show="!showClose"
								:class="['el-select__caret', 'Input__icon', 'el-icon-arrow-up']"
							/>
							<i
								v-if="showClose"
								class="el-select__caret Input__icon el-icon-circle-close"
								@click.stop="handleClearClick"
							/>
						</template>
					</Input>
				</div>
			</template>
			<template>
				<Form
					v-if="filterable"
					:inline="true"
					@submit.native.prevent
				>
					<FormItem label="关键词">
						<Input
							v-model="listQuery.keyword"
							size="small"
							placeholder="请输入关键词查询"
							clearable
							@keyup.enter.native="search()"
						/>
					</FormItem>
					<FormItem>
						<Row :gutter="5">
							<Col :span="12">
								<Button
									type="primary"
									size="small"
									icon="el-icon-search"
									@click="search()"
								>
									{{t("common.search")}}
								</Button>
							</Col>
							<Col :span="12">
								<Button
									size="small"
									icon="el-icon-refresh-right"
									@click="reset()"
								>
									{{t("common.reset")}}
								</Button>
							</Col>
						</Row>
					</FormItem>
				</Form>
				<McTable
					v-loading="listLoading"
					:data="list"
					:border="false"
					highlight-current-row
					:has-n-o="false"
					height="300"
					@row-click="rowClick"
				>
					<template v-if="columnOptions.length">
						<TableColumn
							v-if="multiple"
							width="35"
						>
							<template #default="scope">
								<Checkbox
									:value="selectedIds.includes(scope.row[propsValue])"
									disabled
									class="table-checkbox"
								>
&nbsp;
								</Checkbox>
							</template>
						</TableColumn>
						<TableColumn
							v-if="!multiple"
							width="35"
						>
							<template #default="scope">
								<Radio
									v-model="checked"
									:label="scope.row[propsValue]"
								>
&nbsp;
								</Radio>
							</template>
						</TableColumn>
						<TableColumn
							type="index"
							width="50"
							label="序号"
							align="center"
						/>
					</template>
					<TableColumn
						v-for="(item, i) in columnOptions"
						:key="i"
						:prop="item.value"
						:label="item.label"
					/>
				</McTable>
				<pagination
					v-if="hasPage"
					:page="listQuery.currentPage"
					:limit="listQuery.pageSize"
					:total="total"
					:pager-count="5"
					class="mb-10"
					@pagination="initData"
				/>
				<div class="fr">
					<Button
						size="small"
						@click="closePopover"
					>
						{{t("取消")}}
					</Button>
					<Button
						type="primary"
						size="small"
						@click="confirm()"
					>
						{{t("确定")}}
					</Button>
				</div>
			</template>
		</Popover>
	</div>
</template>

<script>
import {addResizeListener, removeResizeListener} from 'element-ui/src/utils/resize-event';
import McTable from '../table';
import {getScriptFunc,t} from '../../utils';
import {Popover, Tag, Input, Form, FormItem, Row, Col, Button, TableColumn, Checkbox, Radio} from 'element-ui';
export default {
	name:'McPopupTableSelect',
	components:{
		McTable,
		Popover, Tag, Input, Form, FormItem, Row, Col, Button, TableColumn, Checkbox, Radio,
	},
	inject:{
		elForm:{
			default:'',
		},
		elFormItem:{
			default:'',
		},
	},
	model:{
		prop:'value',
		event:'input',
	},
	props:{
		value:{
			type:[String, Number, Array],
			default:'',
		},
		rowIndex:{
			default:null,
			type:Number,
		},
		formData:{
			type:Object,
		},
		templateJson:{
			type:Array,
			default: () => [],
		},
		interfaceId:{
			type:String,
			default:'',
		},
		placeholder:{
			type:String,
			default:'请选择',
		},
		propsValue:{
			type:String,
			default:'id',
		},
		relationField:{
			type:String,
			default:'fullName',
		},
		popupType:{
			type:String,
			default:'popover',
		},
		popupTitle:{
			type:String,
			default:'选择数据',
		},
		popupWidth:{
			type:String,
			default:'800px',
		},
		field:{
			type:String,
			default:'',
		},
		columnOptions:{
			type:Array,
			default: () => [],
		},
		hasPage:{
			type:Boolean,
			default:false,
		},
		pageSize:{
			type:Number,
			default:20,
		},
		multiple:{
			type:Boolean,
			default:false,
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		filterable:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:true,
		},
		collapseTags:{
			type:Boolean,
			default:false,
		},
		size:String,
	},
	data(){
		return {
			t,
			list:[],
			innerValue:'',
			listQuery:{
				keyword:'',
				currentPage:1,
				pageSize:20,
			},
			total:0,
			checked:'',
			checkedTxt:'',
			checkedRow:{},
			selectedData:[],
			selectedIds:[],
			tagsList:[],
			listLoading:false,
			inputHovering:false,
			inputWidth:0,
			initialInputHeight:0,
		};
	},
	computed:{
		showClose(){
			const hasValue = this.multiple
				? Array.isArray(this.value) && this.value.length > 0
				: this.value !== undefined && this.value !== null && this.value !== '';
			const criteria
                = this.clearable && !this.selectDisabled && this.inputHovering && hasValue;
			return criteria;
		},
		currentPlaceholder(){
			if(this.multiple && Array.isArray(this.value) && this.value.length){
				return '';
			}else{
				return this.placeholder;
			}
		},
		selectDisabled(){
			return this.disabled || (this.elForm || {}).disabled;
		},
		_elFormItemSize(){
			return (this.elFormItem || {}).elFormItemSize;
		},
		selectSize(){
			return this.size || this._elFormItemSize || (this.$ELEMENT || {}).size;
		},
		collapseTagSize(){
			return ['small', 'mini'].indexOf(this.selectSize) > -1 ? 'mini' : 'small';
		},
	},
	watch:{
		value(val){
			this.setDefault();
		},
		selectDisabled(){
			this.$nextTick(() => {
				this.resetInputHeight();
			});
		},
	},
	created(){
		this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
		this.setDefault();
	},
	mounted(){
		addResizeListener(this.$el, this.handleResize);

		const reference = this.$refs.reference;
		if(reference && reference.$el){
			const sizeMap = {
				medium:36,
				small:32,
				mini:28,
			};
			const input = reference.$el.querySelector('input');
			this.initialInputHeight
                = input.getBoundingClientRect().height || sizeMap[this.selectSize];
		}
		if(this.multiple){
			this.resetInputHeight();
		}
		this.$nextTick(() => {
			if(reference && reference.$el){
				this.inputWidth = reference.$el.getBoundingClientRect().width;
			}
		});
		this.setDefault();
	},
	beforeUnmount(){
		if(this.$el && this.handleResize) removeResizeListener(this.$el, this.handleResize);
	},
	methods:{
		closePopover(){
			this.$refs.popover.doClose();
		},
		initData(){
			if(!this.interfaceId) return;
			this.listLoading = true;
			const paramList = this.getParamList();
			const columnOptions = this.columnOptions.map((o) => o.value);
			const query = {
				...this.listQuery,
				interfaceId:this.interfaceId,
				propsValue:this.propsValue,
				relationField:this.relationField,
				columnOptions:columnOptions.join(','),
				paramList,
			};
			this.getDataInterfaceDataSelect(this.interfaceId, query)
				.then((res) => {
					this.list = res.data.list;
					this.total = res.data.pagination.total;
					this.listLoading = false;
				})
				.catch(() => {
					this.listLoading = false;
				});
		},
		getDataInterfaceDataSelect(id, data){
			//return this.$httpService({
			//	url:`/api/system/DataInterface/${id}/Action/List`,
			//	method:'post',
			//	data,
			//});
			return new Promise((resolve)=>resolve('接口未迁移'));
		},
		getParamList(){
			const templateJson = this.templateJson;
			for(let i = 0; i < templateJson.length; i++){
				if(templateJson[i].relationField && this.formData){
					if(templateJson[i].relationField.includes('-')){
						const tableVModel = templateJson[i].relationField.split('-')[0];
						const childVModel = templateJson[i].relationField.split('-')[1];
						templateJson[i].defaultValue
                            = (this.formData[tableVModel]
                            	&& this.formData[tableVModel][this.rowIndex]
                            	&& this.formData[tableVModel][this.rowIndex][childVModel])
                            	|| '';
					}else{
						templateJson[i].defaultValue
                            = this.formData[templateJson[i].relationField] || '';
					}
				}
			}
			return templateJson;
		},
		interfaceDataHandler(data){
			if(!data.dataProcessing) return data.list;
			const dataHandler = getScriptFunc.call(this, data.dataProcessing);
			if(!dataHandler) return data.list;
			return dataHandler(data.list);
		},
		search(){
			this.initData();
			this.listQuery.currentPage = 1;
			this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
		},
		reset(){
			this.listQuery.keyword = '';
			this.listQuery.currentPage = 1;
			this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
			this.initData();
		},
		openDialog(){
			if(this.disabled) return;
			this.reset();
		},
		confirm(){
			if(this.multiple){
				this.innerValue = '';
				this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
				this.selectedIds = this.selectedData.map((o) => o[this.propsValue]);
				this.$emit('input', this.selectedIds);
				this.$emit('change', this.selectedIds, this.selectedData);
			}else{
				if(!this.checked){
					this.innerValue = '';
					this.checkedRow = {};
					this.$emit('input', '');
					this.$emit('change', '', {});
					this.closePopover();
					return;
				}
				this.innerValue = this.checkedTxt;
				this.$emit('input', this.checked);
				this.$emit('change', this.checked, this.checkedRow);
			}
			this.closePopover();
		},
		rowClick(row){
			if(this.multiple){
				const boo = this.selectedData.some(
					(o) => o[this.propsValue] === row[this.propsValue],
				);
				if(boo){
					this.selectedData = this.selectedData.filter(
						(o) => o[this.propsValue] !== row[this.propsValue],
					);
					this.selectedIds = this.selectedIds.filter((o) => o !== row[this.propsValue]);
				}else{
					this.selectedData.push(row);
					this.selectedIds.push(row[this.propsValue]);
				}
			}else{
				this.checked = row[this.propsValue];
				this.checkedTxt = row[this.relationField];
				this.checkedRow = row;
			}
		},
		setDefault(){
			if(!this.value || (this.multiple && !this.value.length)){
				this.innerValue = '';
				this.checked = '';
				this.selectedIds = [];
				this.selectedData = [];
				this.tagsList = [];
                // if (!this.field) return
                // let relationData = this.$store.state.generator.relationData
                // this.$set(relationData, this.field, [])
                // this.$store.commit('generator/UPDATE_RELATION_DATA', relationData)
				return;
			}
			if(!this.interfaceId) return;
			const arr = this.multiple ? this.value : [this.value];
			if(this.multiple && !Array.isArray(this.value)){
				this.value = [];
				arr = [];
			}
			const paramList = this.getParamList();
			const query = {
				ids:arr,
				interfaceId:this.interfaceId,
				propsValue:this.propsValue,
				relationField:this.relationField,
				paramList,
			};
			this.getDataInterfaceDataInfoByIds(this.interfaceId, query).then((res) => {
				this.selectedData = res.data;
				this.selectedIds = this.selectedData.map((o) => o[this.propsValue]);
				if(this.multiple){
					this.innerValue = '';
					this.tagsList = JSON.parse(JSON.stringify(this.selectedData));
				}else{
					this.checked = this.value;
					this.innerValue = this.selectedData.length
						? this.selectedData[0][this.relationField]
						: '';
					this.checkedRow = this.selectedData[0];
				}
                // if (!this.field) return
                // let relationData = this.$store.state.generator.relationData
                // this.$set(relationData, this.field, res.data)
                // this.$store.commit('generator/UPDATE_RELATION_DATA', relationData)
				this.$nextTick(() => {
					if(this.multiple){
						this.resetInputHeight();
					}
				});
			});
		},
		getDataInterfaceDataInfoByIds(id, data){
			//return this.$httpService({
			//	url:`/api/system/DataInterface/${id}/Action/InfoByIds`,
			//	method:'POST',
			//	data,
			//});
			return new Promise((resolve)=>resolve('接口未迁移'));
		},
		deleteTag(event, index){
			this.selectedData.splice(index, 1);
			this.confirm();
			event.stopPropagation();
		},
		handleClearClick(event){
			this.checked = '';
			this.innerValue = '';
			this.checkedRow = {};
			this.selectedIds = [];
			this.selectedData = [];
			this.$emit('input', this.checked);
			this.$emit('change', this.checked, this.checkedRow);
			event.stopPropagation();
		},
		resetInputWidth(){
			this.$nextTick(() => {
				if(this.$refs.reference && this.$refs.reference.$el){
					this.inputWidth = this.$refs.reference.$el.getBoundingClientRect().width;
				}else{
					console.warn('reference节点未找到');
				}
			});
		},
		handleResize(){
			this.resetInputWidth();
			if(this.multiple)this.resetInputHeight();
		},
		resetInputHeight(){
			if(this.collapseTags) return;
			this.$nextTick(() => {
				if(!this.$refs.reference) return;
				const inputChildNodes = this.$refs.reference.$el.childNodes;
				const input = [].filter.call(inputChildNodes, (item) => item.tagName === 'INPUT')[0];
				const tags = this.$refs.tags;
				const tagsHeight = tags ? Math.round(tags.getBoundingClientRect().height) : 0;
				const sizeInMap = this.initialInputHeight || 40;
				input.style.height
                    = this.selectedData.length === 0
						? sizeInMap + 'px'
						: Math.max(
							tags ? tagsHeight + (tagsHeight > sizeInMap ? 6 : 0) : 0,
							sizeInMap,
						) + 'px';
			});
		},
	},
};
</script>
<style lang="scss" scoped>
.fr {
    float: right;
}
</style>